package com.apes.crm.car.service;

import com.apes.crm.car.model.CarBase;
import com.apes.crm.car.repository.CarBaseRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

@Service("carBaseService")
public class CarBaseService extends DomainService {

    @Autowired
    CarBaseRepository carBaseRepository;


    /**
     * 创建基础车辆信息
     * @param request
     * @return
     */
    public CarBase create(SimpleRequest request){
        CarBase carBase = request.getO(CarBase.class);

        List<CarBase> carBaseList = carBaseRepository.findByFrameNumber(carBase.getFrameNumber());
        if(carBaseList.size() > 0) {
            throw new RuntimeException("已存在相同车辆内码或者车架号的车辆，车辆编码为" +
                    carBaseList.stream().map(item -> item.getId())
                            .reduce(new BinaryOperator<String>() {
                                @Override
                                public String apply(String s1, String s2) {
                                    return s1 + ";" + s2;
                                }
                            }).get());
        }

        return carBaseRepository.saveAndFlush(carBase);
    }

    /***
     * 修改基础车辆信息
     * @param request
     * @return
     */
    public CarBase update(SimpleRequest request){
        CarBase carBase = request.getO(CarBase.class);

        List<CarBase> carBaseList = carBaseRepository.findByFrameNumber(carBase.getFrameNumber());

        List<CarBase> duplicates = carBaseList.stream().filter(item -> !item.getId().equals(carBase.getId())).collect(Collectors.toList());

        if(duplicates.size() > 0){
            throw new RuntimeException("已存在相同车辆内码或者车架号的车辆，车辆编码为" +
                    duplicates.stream().map(item -> item.getId())
                            .reduce(new BinaryOperator<String>() {
                                @Override
                                public String apply(String s1, String s2) {
                                    return s1 + ";" + s2;
                                }
                            }));
        }

        return carBaseRepository.saveAndFlush(carBase);
    }



}
